package com.smxy.daydayup.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.smxy.daydayup.mapper.SectionMaterialMapper;
import com.smxy.daydayup.mapper.TeacherMapper;
import com.smxy.daydayup.pojo.CourseTalk;
import com.smxy.daydayup.pojo.SectionMaterial;
import com.smxy.daydayup.pojo.SectionTree;
import com.smxy.daydayup.pojo.Teacher;
import com.smxy.daydayup.pojo.User;
import com.smxy.daydayup.pojo.ao.CourseContextAO;
import com.smxy.daydayup.pojo.dto.SectionContent;
import com.smxy.daydayup.service.CourseTalkService;
import com.smxy.daydayup.service.SectionTreeService;
import com.smxy.daydayup.util.IdUtil;
import com.smxy.daydayup.util.JwtUtils;
import com.smxy.daydayup.util.datetime.DateUtil;
import com.smxy.daydayup.util.result.ResultUtil;
import com.smxy.daydayup.util.result.ReturnResult;
import com.smxy.daydayup.util.result.StatusCode;
import com.smxy.daydayup.util.tree.TreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @team daydayup
 * @time 2021-12-11 23:30
 */

@Api(tags = "章节树控制器")
@RestController
@RequestMapping("/section")
public class SectionController {

    @Autowired
    CourseTalkService courseTalkService;
    @Autowired
    SectionTreeService sectionTreeService;


    @ApiOperation("展示章节的接口(树形目录)")
    @ApiImplicitParam(
            name = "courseId",
            value = "课程id",
            required = true,
            dataTypeClass = Long.class
    )
    @GetMapping("/show")
    public ReturnResult showTreeList(HttpServletRequest request){
        CourseContextAO courseContextAOByToken = JwtUtils.getCourseContextAOByToken(request);
        List<SectionTree> treeList = sectionTreeService.getTreeList(courseContextAOByToken.getCourseId());
        if(treeList!=null){
            return ResultUtil.returnSuccess(treeList,"success");
        }else{
            return ResultUtil.returnFail(StatusCode.DATA_ERROR,"参数错误");
        }
    }

    @ApiOperation("修改章节信息的接口")
    @ApiImplicitParam(
            name = "courseId",
            value = "课程id",
            required = false,
            dataTypeClass = Long.class
    )
    @PostMapping("/update")
    public ReturnResult updateTreeList(@ApiParam("章节树集合") @RequestBody List<SectionTree> treeList,
                                       HttpServletRequest request){
        CourseContextAO courseContextAOByToken = JwtUtils.getCourseContextAOByToken(request);
        List<SectionTree> resultList = TreeUtils.resolveTree(treeList);

        if(sectionTreeService.updateTree(resultList,courseContextAOByToken.getCourseId())>0){
            return ResultUtil.returnSuccess();
        }else{
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"服务器异常");
        }
    }

    @ApiOperation("修改章节文本")
    @PostMapping("/updatecontent")
    public ReturnResult updateContent(@ApiParam("章节内容集合") @RequestBody List<SectionContent> contents){
        SectionTree sectionTree=null;
        for(int i=0;i<contents.size();i++){
            sectionTree=new SectionTree(contents.get(i).getSectionId(),null,null,null,contents.get(i).getSectionContent(),null);
            sectionTreeService.updateByPrimaryKeySelective(sectionTree);
        }
        return ResultUtil.returnFail(StatusCode.SUCCESS,"成功");
    }

    @ApiOperation("测试生成初始化树目录")
    @ApiImplicitParam(
            name = "courseId",
            value = "课程id",
            required = true,
            dataTypeClass = Long.class
    )
    @PostMapping("/init")
    public ReturnResult initTree(@RequestParam("courseId") Integer courseId){
        List<SectionTree> initTree = TreeUtils.constructInitTree(courseId);
        if(sectionTreeService.updateTree(initTree,courseId)>0){
            return ResultUtil.returnSuccess();
        }else{
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"服务器异常");
        }
    }


    @ApiOperation("查询此课程所有发布的讨论的接口")
    @ApiImplicitParam(
            name = "sectionId",
            value = "课程章节id",
            required = true,
            dataTypeClass = Long.class
    )
    @GetMapping("/talk")   //通过课程id去查询这个课程下面的所有讨论(基本的查询语句)
    public ReturnResult selectTalk(@RequestParam("sectionId") Integer sectionId) {
        return ResultUtil.returnSuccess(courseTalkService.selectAllTalk(sectionId), "讨论信息");
    }

    @ApiOperation("发布讨论的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "sectionId",
                    value = "课程章节id",
                    required = true,
                    dataTypeClass = Integer.class
            ),
            @ApiImplicitParam(
                    name = "courseTalkTitle",
                    value = "课程讨论标题",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "courseTalkContent",
                    value = "课程讨论内容",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "userId",
                    value = "用户id",
                    required = true,
                    dataTypeClass = String.class
            )
    })
    @PostMapping("/addtalk")    //通过课程id向该课程添加基本的讨论信息(基本的插入语句)
    public ReturnResult insertTalk(@RequestParam("sectionId") Integer sectionId,
                                   @RequestParam("courseTalkTitle") String courseTalkTitle,
                                   @RequestParam("courseTalkContent") String courseTalkContent,
                                   HttpServletRequest request) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        CourseTalk courseTalk = new CourseTalk(null, IdUtil.getBaseID(), sectionId, courseTalkTitle, courseTalkContent, userInfoByToken.getUserId(), DateUtil.getNowDate(), DateUtil.getNowDate(), 0);
        return ResultUtil.returnSuccess(courseTalkService.insertSelective(courseTalk), "发布讨论");
    }

    @ApiOperation("保存获赞个数的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "courseTalkId",
                    value = "课程讨论id",
                    required = true,
                    dataTypeClass = Long.class
            ),
            @ApiImplicitParam(
                    name = "great",
                    value = "点赞数",
                    required = true,
                    dataTypeClass = Integer.class
            )
    })
    @PostMapping("/savegreat")    //通过讨论的id来不断修改讨论的数(基本的修改语句)
    public ReturnResult savegreat(@RequestParam("courseTalkId") Integer courseTalkId) {
        CourseTalk courseTalk = new CourseTalk(courseTalkId, null, null, null, null, null, null, null, 1);
        return ResultUtil.returnSuccess(courseTalkService.updateByPrimaryKeySelective(courseTalk), "点赞数");
    }

    @ApiOperation("查询此讨论的回复的接口")
    @ApiImplicitParam(
            name = "courseTalkNumber",
            value = "课程讨论编号",
            required = true,
            dataTypeClass = String.class
    )
    @GetMapping("/reply")      //通过课程讨论编号来查询这个讨论下的回复（回复的标题是空的）
    public ReturnResult selectReply(@RequestParam("courseTalkNumber") String courseTalkNumber) {
        return ResultUtil.returnSuccess(courseTalkService.selectReply(courseTalkNumber), "回复信息");
    }

    @ApiOperation("回复讨论的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "courseTalkNumber",
                    value = "课程讨论编号",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "sectionId",
                    value = "课程章节id",
                    required = true,
                    dataTypeClass = Integer.class
            ),
            @ApiImplicitParam(
                    name = "courseTalkContent",
                    value = "课程讨论内容",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "userId",
                    value = "用户id",
                    required = true,
                    dataTypeClass = String.class
            )
    })
    @PostMapping("/replytalk")    //通过课程讨论编号来插入回复的基本信息（讨论标题为空代表是回复的信息）（基本的插入语句）
    public ReturnResult insertReplyTalk(@RequestParam("courseTalkNumber") String courseTalkNumber,
                                        @RequestParam("sectionId") Integer sectionId,
                                        @RequestParam("courseTalkContent") String courseTalkContent,
                                        HttpServletRequest request) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        CourseTalk courseTalk = new CourseTalk(null, courseTalkNumber, sectionId, null, courseTalkContent, userInfoByToken.getUserId(), DateUtil.getNowDate(), DateUtil.getNowDate(), 0);
        return ResultUtil.returnSuccess(courseTalkService.insertSelective(courseTalk), "回复讨论");
    }

    @PostMapping("/listSectionMaterial")
    public ReturnResult<List<SectionMaterial>> fetch(@RequestParam("sectionId") Integer sectionId, @RequestParam("catalog") SectionMaterial.CATALOG catalog) {
        List<SectionMaterial> sectionMaterials = sectionMaterialMapper.selectList(Wrappers.lambdaQuery(SectionMaterial.class)
                .eq(SectionMaterial::getCatalog, catalog)
                .eq(SectionMaterial::getSectionId, sectionId)
        );

        return ResultUtil.returnSuccess(sectionMaterials, "");
    }

    @Resource
    SectionMaterialMapper sectionMaterialMapper;
    @PostMapping("/bondSectionMaterial")
    public ReturnResult uploadSectionMaterial(@RequestBody @Validated SectionMaterial sectionMaterial) {
        sectionMaterialMapper.insert(sectionMaterial);
        return ResultUtil.returnSuccess();
    }
    @Autowired
    TeacherMapper teacherMapper;
    @PostMapping("/unbondSectionMaterial")
    public ReturnResult unbondSectionMaterial(@RequestBody SectionMaterial sectionMaterial, HttpServletRequest request) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        SectionTree sectionTree = sectionTreeService.selectByPrimaryKey(sectionMaterial.getSectionId());
        if (sectionTree == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未找到章节");
        }
        Teacher cond = new Teacher();
        cond.setCourseId(sectionTree.getCourseId());
        cond.setUserId(userInfoByToken.getUserId());
        Integer exist = teacherMapper.checkExist(cond);
        if (exist == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未找到所属课程章节");
        }

        sectionMaterialMapper.deleteById(sectionMaterial.getId());
        return ResultUtil.returnSuccess();
    }
}
